import EchartsComponent, { MyChartOption } from '@/components/EchartsComponent';
import HandleBtn from '@/components/HandleBar/btn';
import { ProColumns, ProForm, ProFormDateRangePicker, ProFormSelect } from '@/components/Pro';
import { getEmptyOptions } from '@/dictionary';
import SelectedTags from '@/pages/SiteMonitor/HisCurve/components/SelectedTags';
import SwitchButtons from '@/pages/SiteMonitor/HisCurve/components/SwitchButtons';
import {
  historyCurveControllerStatistics,
  historyCurveControllerStatisticsExport,
  historyCurveControllerStatisticsList,
} from '@/services/ess/historicalCurve';
import { downloadFetch } from '@/utils/downloadFile';
import { DownloadOutlined } from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { Button, message } from 'antd';
import { DatePickerProps } from 'antd/lib/date-picker';
import dayjs from 'dayjs';
import React, { useRef, useState } from 'react';

type IProps = {
  tagList: string[];
  reset: () => void;
};

interface viewTagInter extends API.DataColumnDTO {
  uniqueId?: string;
}

const dateFormatMap = {
  date: 'YYYY-MM-DD',
  month: 'YYYY-MM',
  year: 'YYYY',
};
const dateUnitMap = {
  date: 'DAY',
  month: 'MONTH',
  year: 'YEAR',
};
const SumData: React.FC<IProps> = (props) => {
  const { tagList, reset } = props;
  const chartRef = useRef(null);
  const tableRef = useRef(null);
  const formRef = useRef(null);
  const intl = useIntl();
  const [currentTags, setCurrentTags] = useState<viewTagInter[]>();
  const [type, setType] = useState('chart');
  const [dimension, setDimension] = useState('date');
  const [selectedDate, setSelectedDate] = useState([dayjs().subtract(6, 'day'), dayjs()]);
  const [chartOptions, setChartOptions] = useState(getEmptyOptions());
  const dimensionsOptions = [
    {
      label: intl.formatMessage({ id: 'hisCurve.day' }),
      value: 'date',
    },
    {
      label: intl.formatMessage({ id: 'hisCurve.month' }),
      value: 'month',
    },
    {
      label: intl.formatMessage({ id: 'hisCurve.year' }),
      value: 'year',
    },
  ];
  const submitCloseTags = (tags: viewTagInter[]) => {
    setCurrentTags(tags);
  };
  const disabledDate: DatePickerProps['disabledDate'] = (current, { from }) => {
    if (from) {
      switch (dimension) {
        case 'date':
          return Math.abs(current.diff(from, 'days')) >= 7;
        case 'month':
          return Math.abs(current.diff(from, 'month')) >= 36;
        case 'year':
          return Math.abs(current.diff(from, 'years')) >= 5;
      }
    }
    return false;
  };
  const baseColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'hisCurve.no' }),
      valueType: 'index',
      dataIndex: 'id',
      width: 80,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'global.date' }),
      dataIndex: 'date',
      width: 150,
    },
  ];
  const formatterOptions = (data: API.DataCurveDTO): MyChartOption => {
    const seriesData = data.yaxis.map((item) => {
      return {
        type: 'bar',
        data: item.pointsValues,
        name: item.title + '' + (item?.unit ? `(${item?.unit})` : ''),
      };
    });
    return {
      xAxis: {
        axisTick: {
          inside: true,
        },
        data: data?.xaxis,
      },
      yAxis: {
        type: 'value',
      },
      legend: {},
      tooltip: {
        trigger: 'axis',
      },
      series: seriesData,
    };
  };
  const getDataIndex = (item: API.DataColumnDTO): string | undefined => {
    switch (item.nodeType) {
      case 'ROOT':
        return item.dataAttr;
      case 'AREA':
        return `${item.areaId ? item.areaId + '_' : ''}${item.dataAttr}`;
      case 'DEVICE_GROUP':
        return `${item.areaId ? item.areaId + '_' : ''}${
          item.deviceType ? item.deviceType + '_' : ''
        }${item.dataAttr}`;
      case 'DEVICE':
        return `${item.deviceCode ? item.deviceCode + '_' : ''}${item.dataAttr}`;
      default:
        return '';
    }
  };
  const getElseColumns = (tableData: API.DataColumnDTO[]): ProColumns[] => {
    return tableData?.map((item: API.DataColumnDTO) => {
      return {
        title:
          item.deviceType === 'STATION'
            ? `${item.dataName}${item.unit ? `(${item.unit})` : ''}`
            : `${item.areaName ? item.areaName + '_' : ''}${
                item.deviceName ? item.deviceName + '_' : ''
              }${item.dataName ? item.dataName : ''}${item.unit ? `(${item.unit})` : ''}`,
        dataIndex: getDataIndex(item),
        width: 150,
      };
    });
  };
  const exportIncomeReport = () => {
    const params = {
      startDate:
        dimension !== 'date'
          ? dayjs(selectedDate[0]).startOf(dimension).format('YYYY-MM-DD')
          : dayjs(selectedDate[0]).format('YYYY-MM-DD'),
      endDate:
        dimension !== 'date'
          ? dayjs(selectedDate[1]).startOf(dimension).format('YYYY-MM-DD')
          : dayjs(selectedDate[1]).format('YYYY-MM-DD'),
      columnList: currentTags,
      dateUnit: dateUnitMap[dimension],
    };
    downloadFetch(historyCurveControllerStatisticsExport, params);
  };
  const [elseColumns, setElseColumns] = useState<ProColumns[]>([]);
  const getColumns = baseColumns.concat(elseColumns);
  const exportChart = () => {
    const chart = chartRef?.current?.instance();
    if (chart) {
      // 先获取 SVG 数据
      const svgUrl = chart.getDataURL({
        type: 'svg',
        pixelRatio: 2,
        backgroundColor: '#fff',
      });

      // 创建 Image 对象
      const img = new Image();
      img.src = svgUrl;
      img.onload = () => {
        // 创建 canvas
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');

        // 设置 canvas 尺寸为图表尺寸
        canvas.width = chart.getWidth();
        canvas.height = chart.getHeight();
        // 先填充白色背景
        if (ctx) {
          ctx.fillStyle = '#fff';
          ctx.fillRect(0, 0, canvas.width, canvas.height);

          // 绘制图像
          ctx.drawImage(img, 0, 0);
        }

        // 导出为 PNG
        const pngUrl = canvas.toDataURL('image/png');
        const link = document.createElement('a');
        link.download = `${intl.formatMessage({
          id: 'statistics.analyze.historyCurveData',
        })}_${dayjs().format('YYYY-MM-DD_HH:mm:ss')}.png`;
        link.href = pngUrl;
        link.click();
      };
    }
  };
  const handleSearch = () => {
    const params = {
      startDate:
        dimension !== 'date'
          ? dayjs(selectedDate[0]).startOf(dimension).format('YYYY-MM-DD')
          : dayjs(selectedDate[0]).format('YYYY-MM-DD'),
      endDate:
        dimension !== 'date'
          ? dayjs(selectedDate[1]).startOf(dimension).format('YYYY-MM-DD')
          : dayjs(selectedDate[1]).format('YYYY-MM-DD'),
      columnList: currentTags,
      dateUnit: dateUnitMap[dimension],
    };
    if (!params?.columnList.length) {
      message.warning(intl.formatMessage({ id: 'global.leastOne' }));
      return false;
    }
    if (type === 'chart') {
      historyCurveControllerStatistics(params).then((res) => {
        if (res.success) {
          chartRef?.current?.instance().clear();
          setChartOptions(formatterOptions(res.data));
        }
      });
    } else {
      tableRef?.current?.reload();
    }
  };
  return (
    <>
      <div>
        <ProForm
          formRef={formRef}
          layout={'inline'}
          onReset={() => {
            reset();
            setDimension('date');
            setSelectedDate([dayjs().subtract(6, 'day'), dayjs()]);
            if (type === 'chart') {
              chartRef?.current?.instance().clear();
              setChartOptions(getEmptyOptions());
            } else {
              tableRef?.current?.reload();
            }
          }}
          submitter={{
            searchConfig: {
              submitText: intl.formatMessage({ id: 'global.search' }),
            },
          }}
          onFinish={handleSearch}
        >
          <ProFormSelect
            name={'dimension'}
            initialValue={'date'}
            label={intl.formatMessage({ id: 'hisCurve.dimensions' })}
            options={dimensionsOptions}
            fieldProps={{
              value: dimension,
              allowClear: false,
              onChange: (value: string) => {
                setDimension(value);
                setSelectedDate(
                  value === 'date'
                    ? [dayjs().subtract(6, 'day'), dayjs()]
                    : value === 'month'
                    ? [dayjs().subtract(5, 'month'), dayjs()]
                    : [dayjs().subtract(2, 'year'), dayjs()],
                );
              },
            }}
          ></ProFormSelect>
          <ProFormDateRangePicker
            name={'dateRange'}
            label={intl.formatMessage({ id: 'hisCurve.timeSelect' })}
            fieldProps={{
              allowClear: false,
              value: selectedDate,
              picker: dimension,
              format: dateFormatMap[dimension],
              disabledDate: disabledDate,
              onCalendarChange: (dates) => {
                setSelectedDate(dates);
              },
            }}
          ></ProFormDateRangePicker>
        </ProForm>
        <SelectedTags submitCloseTags={submitCloseTags} tagList={tagList}></SelectedTags>
        <div style={{ marginTop: 20 }}>
          <SwitchButtons
            changeButtons={(value: string) => {
              setType(value);
              setTimeout(() => {
                const params = {
                  startDate:
                    dimension !== 'date'
                      ? dayjs(selectedDate[0]).startOf(dimension).format('YYYY-MM-DD')
                      : dayjs(selectedDate[0]).format('YYYY-MM-DD'),
                  endDate:
                    dimension !== 'date'
                      ? dayjs(selectedDate[1]).startOf(dimension).format('YYYY-MM-DD')
                      : dayjs(selectedDate[1]).format('YYYY-MM-DD'),
                  columnList: currentTags,
                  dateUnit: dateUnitMap[dimension],
                };
                if (!params?.columnList?.length) {
                  message.warning(intl.formatMessage({ id: 'global.leastOne' }));
                  return false;
                }
                if (value === 'chart') {
                  historyCurveControllerStatistics(params).then((res) => {
                    if (res.success) {
                      chartRef?.current?.instance().clear();
                      setChartOptions(formatterOptions(res.data));
                    }
                  });
                } else {
                  tableRef?.current?.reload();
                }
              }, 0);
            }}
          ></SwitchButtons>
        </div>
        {type === 'chart' ? (
          <div style={{ position: 'relative', marginTop: 20 }}>
            <Button
              icon={<DownloadOutlined />}
              onClick={exportChart}
              style={{ position: 'absolute', right: 0, top: -60 }}
            >
              {intl.formatMessage({ id: 'statistics.analyze.exportImage' })}
            </Button>
            <EchartsComponent option={chartOptions} height={400} ref={chartRef}></EchartsComponent>
          </div>
        ) : (
          <div style={{ marginTop: 20 }}>
            <ProTable
              toolBarRender={() => {
                return (
                  <HandleBtn
                    key="export"
                    handleType="export"
                    onClick={() => {
                      exportIncomeReport();
                    }}
                  >
                    {intl.formatMessage({ id: 'statistics.common.export' })}
                  </HandleBtn>
                );
              }}
              actionRef={tableRef}
              columns={getColumns}
              search={false}
              params={{
                type: type,
              }}
              request={async () => {
                if (type === 'list') {
                  const params = {
                    startDate:
                      dimension !== 'date'
                        ? dayjs(selectedDate[0]).startOf(dimension).format('YYYY-MM-DD')
                        : dayjs(selectedDate[0]).format('YYYY-MM-DD'),
                    endDate:
                      dimension !== 'date'
                        ? dayjs(selectedDate[1]).startOf(dimension).format('YYYY-MM-DD')
                        : dayjs(selectedDate[1]).format('YYYY-MM-DD'),
                    dateUnit: dateUnitMap[dimension],
                    columnList: currentTags,
                  };
                  if (!params?.columnList.length) {
                    message.warning(intl.formatMessage({ id: 'global.leastOne' }));
                    return false;
                  }
                  const res = await historyCurveControllerStatisticsList(params);
                  if (res.success) {
                    setElseColumns(getElseColumns(res?.data?.dataColumnList));
                  }
                  return {
                    success: res.success,
                    data: res?.data?.dataList,
                  };
                }
              }}
            ></ProTable>
          </div>
        )}
      </div>
    </>
  );
};
export default SumData;
